use std::time::Duration;
use super::PlayerState;
use super::state::{VideoInfo, AudioInfo};
use tauri::State;
use anyhow::Result;
use serde::Serialize;

#[derive(Debug, Clone, Serialize)]
pub struct MediaInfo {
    pub duration: Duration,
    pub video_info: Option<VideoInfo>,
    pub audio_info: Option<AudioInfo>,
}

#[tauri::command]
pub async fn load_media(path: String, state: State<'_, PlayerState>) -> Result<MediaInfo, String> {
    log::info!("Loading media file: {}", path);
    state.load_media(&path).map_err(|e| e.to_string())?;
    
    let state_guard = state.inner.lock().unwrap();
    let player_state = state_guard.state.lock().unwrap();
    let info = MediaInfo {
        duration: player_state.duration.unwrap_or_default(),
        video_info: player_state.video_info.clone(),
        audio_info: player_state.audio_info.clone(),
    };
    
    log::info!("Media info: {:#?}", info);
    Ok(info)
}

#[tauri::command]
pub async fn play(state: State<'_, PlayerState>) -> Result<(), String> {
    state.play().map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn pause(state: State<'_, PlayerState>) -> Result<(), String> {
    log::info!("Pause command received");
    state.pause().map_err(|e| e.to_string())?;
    log::info!("Pause command executed successfully");
    Ok(())
}

#[tauri::command]
pub async fn stop(state: State<'_, PlayerState>) -> Result<(), String> {
    state.stop().map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn seek(position: Duration, state: State<'_, PlayerState>) -> Result<(), String> {
    state.seek(position).map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn set_volume(volume: f32, state: State<'_, PlayerState>) -> Result<(), String> {
    state.set_volume(volume).map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn get_position(state: State<'_, PlayerState>) -> Result<Duration, String> {
    Ok(state.inner.lock().unwrap().state.lock().unwrap().current_position)
}

#[tauri::command]
pub async fn get_duration(state: State<'_, PlayerState>) -> Result<Option<Duration>, String> {
    Ok(state.inner.lock().unwrap().state.lock().unwrap().duration)
}

#[tauri::command]
pub async fn is_playing(state: State<'_, PlayerState>) -> Result<bool, String> {
    Ok(state.inner.lock().unwrap().state.lock().unwrap().is_playing())
}
